package com.wealth.member.web.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.wealth.lottery.entity.LotteryActivity;
import com.wealth.lottery.entity.LotteryNumber;
import com.wealth.lottery.entity.LotteryRecord;
import com.wealth.lottery.enums.LotteryActivityStatusEnums;
import com.wealth.lottery.enums.LotteryActivityTypeEnums;
import com.wealth.lottery.repository.LotteryRecordDao;
import com.wealth.lottery.service.ILotteryActivityService;
import com.wealth.lottery.service.ILotteryNumberService;
import com.wealth.lottery.service.ILotteryRecordService;
import com.wealth.lottery.vo.LotteryActivityVO;
import com.wealth.member.entity.Member;
import com.wealth.member.entity.Membership;
import com.wealth.member.service.IMemberService;
import com.wealth.member.service.IMembershipService;
import com.wealth.member.service.IReturncashService;
import com.wealth.platform.entity.Account;
import com.wealth.platform.service.IAccountService;
import com.wealth.system.entity.Corporation;
import com.wealth.system.service.ICorpService;
import com.wealth.system.web.controller.BaseController;

import iaas.redis.RedisService;
import iaas.utils.CommonUtil;
import iaas.utils.ResultObject;

/**
 * @author chan 个人中心
 */

@Controller
@RequestMapping("/manage/member")
public class MemberController extends BaseController {

	Logger logger = Logger.getLogger(MemberController.class);

	@Autowired
	private IMembershipService membershipService;
	@Autowired
	private IMemberService memberService;
	@Autowired
	private IAccountService accountService;
	@Autowired
	private RedisService redisService;
	@Autowired
	private IReturncashService returncashService;
	@Autowired
	private ILotteryRecordService lotteryRecordService;
	@Autowired
	private ICorpService corpService;
	@Autowired 
	private ILotteryNumberService iLotteryNumberService;
	@Autowired
	private ILotteryActivityService activityService;
	@Autowired
	private LotteryRecordDao lotteryRecordDao;
	/**
	 * 主页
	 */
	@RequestMapping
	public String index(Model model) {
		try {
			Membership membership = membershipService
					.getMemberShipByMemberIdAndCorpId(memberid, corpid);
			model.addAttribute("membership", membership);
			return "member/index";
		} catch (Exception e) {
			return "system/500";
		}
	}

	/**
	 * 个人资料
	 */
	@RequestMapping(value = "/profile")
	public String profileForm(Model model) {
		try {
			return "member/profile";
		} catch (Exception e) {
			return "system/500";
		}
	}

	/**
	 * 手机绑定页面
	 */
	@RequestMapping(value = "/telephone")
	public String bindTelephoneForm(Model model) {
		try {
			Membership membership = membershipService
					.getMemberShipByMemberIdAndCorpId(memberid, corpid);
			Member member = membership.getMember();
			model.addAttribute("member", member);
			return "member/telephone";
		} catch (Exception e) {
			return "system/500";
		}
	}

	/**
	 * 手机绑定
	 */
	@RequestMapping(value = "/telephone", method = RequestMethod.POST)
	@ResponseBody
	public ResultObject bindTelephone(@RequestParam String telephone,
			@RequestParam String random, HttpSession session) {
		try {

			/** -------- redis获取验证码 -------- **/
			String randomInRedis = redisService.get("redis_login_" + telephone);
			if (StringUtils.isBlank(randomInRedis)) {
				return new ResultObject("500", "短信验证码超时失效", null);
			}
			if (!randomInRedis.equals(random)) {
				return new ResultObject("510", "短信验证码错误", null);
			}

			ResultObject rs = memberService.bindTelephone(memberid, corpid,
					telephone);
			//更新session 中的 memberid
			Member member = memberService.findMemberByUsername(rs.getResult().toString());
			session.setAttribute("memberid", member.getId());
			/**给用户用添加一次抽奖机会*/
			if(rs.getCode()=="000"){
				/**查询正常启用的活动  每个用户最多十次抽奖机会*/
				List<LotteryActivity> activitylist = activityService.getByStatus();
				if(activitylist.size()>0){
					int count = 1;
					LotteryActivity activity = activitylist.get(0);
					LotteryNumber number= iLotteryNumberService.getByMember(memberid, activity.getId());
					if(number!=null){
						int count1 = number.getTotal();
						if(count1>=10){
							count=0;
						}
						number.setTotal(number.getTotal()+count);
						iLotteryNumberService.save(number);
					}else{
						LotteryNumber n_number = new LotteryNumber();
						n_number.setActivity(activity);
						n_number.setMember(new Member(memberid));
						n_number.setTotal(count);
						iLotteryNumberService.save(n_number);
					}
				}
			}
			return rs;
		} catch (Exception e) {
			return new ResultObject("999", "手机绑定失败", "");
		}
	}
	
	
	
 	 /**
	 * 手机绑定Test
	 */ 
	/*@RequestMapping(value = "/telephoneTest", method = RequestMethod.GET)
	@ResponseBody
	public ResultObject bindTelephoneTest(@RequestParam String telephone
			 ) {
		try { 
			ResultObject rs = memberService.bindTelephone(memberid, corpid,
					telephone);
			 
			return rs;
		} catch (Exception e) {
			return new ResultObject("999", "手机绑定失败", "");
		}
	} */
	 
	/**
	 * 银行卡绑定页面
	 */
	@RequestMapping(value = "/bankcard")
	public String bindBankcardForm(Model model) {
		try {
			Membership membership = membershipService
					.getMemberShipByMemberIdAndCorpId(memberid, corpid);
			Account account;
			if (membership.getAccount() != null) {
				account = membership.getAccount();
			} else {
				account = new Account();
			}
			model.addAttribute("account", account);

			return "member/bankcard";
		} catch (Exception e) {
			return "system/500";
		}
	}

	/**
	 * 银行卡绑定
	 */
	@RequestMapping(value = "/bankcard", method = RequestMethod.POST)
	@ResponseBody
	public ResultObject bindBankcard(@RequestParam String bankcard,
			@RequestParam String identitycard, @RequestParam String telephone) {
		try {
			ResultObject rs = accountService.bindBankcard(corpid, memberid,
					bankcard, identitycard, telephone);
			return rs;
		} catch (Exception e) {
			return new ResultObject("999", "银行卡绑定失败", "");
		}
	}

	/**
	 * 跳转到好评返现页面
	 * 
	 * @return
	 */
	@RequestMapping(value = "/returnCash", method = RequestMethod.GET)
	public String returnCashs(Model model) {
		try {
			Corporation corp = corpService.get(corpid);
			String url = corp.getUrl();
			model.addAttribute("url", url);
			return "member/cash";
		} catch (Exception e) {
			e.printStackTrace();
			return "system/500";
		}

	}

	/**
	 * 跳转到好评返现上传图片页面
	 * 
	 * @return
	 */
	@RequestMapping(value = "/upload", method = RequestMethod.GET)
	public String upload() {

		return "member/upload";

	}

	/**
	 * 好评返现
	 */
	@RequestMapping(value = "/returnCash", method = RequestMethod.POST)
	@ResponseBody
	public ResultObject returnCash(String openid, HttpServletRequest request) {
		String[] pic = request.getParameterValues("pics[]");
		Membership membership = membershipService
				.getMemberShipByMemberIdAndCorpId(memberid, corpid);
		if (returncashService.savePic(memberid, membership.getOpenid(), pic[0],
				corpid) == false) {
			return new ResultObject("100", "保存成功", "");
		} else {
			return new ResultObject("200", "保存失败", "");
		}

	}

	public String share() {
		return null;

	}
	
	
	/**
	 * 抽奖记录
	 */
	@RequestMapping(value = "/lotteryRecord", method = RequestMethod.GET)
	public String lotteryRecord(Model model) {
		try {
			List<LotteryRecord> lotteryRecordList = lotteryRecordService.getLotteryRecordByMemberId(memberid);
			/**把用户的观看记录归类*/
			Map<Long, List<LotteryRecord>> map = new HashMap<Long, List<LotteryRecord>>();
			/**把素材归纳*/
			for (LotteryRecord record : lotteryRecordList) {
				if(map.containsKey(record.getLotteryactivity().getId())){
					map.get(record.getLotteryactivity().getId()).add(record);
				}else{
					List<LotteryRecord> recordList =  new ArrayList<LotteryRecord>();
					recordList.add(record);
					map.put(record.getLotteryactivity().getId(),recordList);
				}
			}
			List<LotteryActivityVO> recordList =new ArrayList<LotteryActivityVO>();
			 for (Map.Entry<Long, List<LotteryRecord>> entry : map.entrySet()) {
				 LotteryActivityVO vo = new LotteryActivityVO();
				 vo.setName(entry.getValue().get(0).getLotteryactivity().getName());
				 vo.setRecordList(entry.getValue());
				 recordList.add(vo);
			 }
			model.addAttribute("recordList", recordList);
			return "member/lotteryRecordList";
		} catch (Exception e) {
			return "system/500";
		}
	}
}
